import React, { useCallback } from 'react';
import { evaluationProjectV1AdminControllerAll } from '@/services/auto/evaluationProjectAdmin';
import { Button, Checkbox, Divider, Input, message, Select, Space, Table, Upload, } from 'antd';
import { MinusOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { useRequest } from "ahooks";
import { BooleanNumber, EvaluationProjectType, FileGroup } from "common/utils/data";
import FileUpload from "@/components/FileUpload";
import { SortEnd } from 'react-sortable-hoc';
import { arrayMoveImmutable } from 'array-move';
import TableModal from "./TableModal";
// import GenerateDataModal from "./GenerateDataModal";
import { DragHandle, SortableBody, SortableItem } from "@/components/Drag";
import { DEFAULT_DATA_GROUP } from "@/utils";
import DataTextDetailBtn from "./DataTextDetailBtn";

const { TextArea } = Input;

interface DatasItem{
  key: number;
  projectUuid: string;
  data?: string;
  desc: string;
  name: string;
  defaultShow: BooleanNumber;
  img?: string;
  json?: any;
  group?: string;
}

const emptyArr: DatasItem[] = [];

export default function DataTables(props: {
  value?: DatasItem[];
  onChange?: (value?: DatasItem[]) => void; // 这里暂时不能动态识别onChange了 只认初始值
  dataGroups?: string[];
}){
  const { value = emptyArr, onChange, dataGroups } = props;

  const {
    data: getAllArticleDataTypeData,
    loading: getAllArticleDataTypeLoading,
  } = useRequest(evaluationProjectV1AdminControllerAll)

  const keyFlag = value.map(item=>item.key).join(','); // 是否改过顺序

  const getBody = useCallback((props: any) => (
    <SortableBody
      useDragHandle
      disableAutoscroll
      helperClass="row-dragging"
      onSortEnd={({ oldIndex, newIndex }: SortEnd) => {
        if (oldIndex !== newIndex) {
          const newData = arrayMoveImmutable(value.slice(), oldIndex, newIndex).filter(
            el => !!el,
          );
          onChange?.(newData);
        }
      }}
      {...props}
    />
  ),[keyFlag])

  const getRow = useCallback((props: any) => {
    const index = value.findIndex(x => x.key === props['data-row-key']);
    return <SortableItem index={index} {...props} />;
  },[keyFlag])

  return (
    <Table
      size="small"
      rowKey="key"
      columns={[
        {
          title: '序号',
          dataIndex: 'index',
          className: 'drag-visible',
          render: (val, record, index: number) => {
            return <>
              <span className="mr-[2px]">{index + 1}</span>
              <DragHandle />
            </>
          },
        },
        {
          title: '默认显示',
          dataIndex: 'defaultShow',
          render: (val, record, index: number) => {
            return <Checkbox
              checked={!!val}
              onChange={e => {
                const arr = [...value];
                arr[index].defaultShow = e.target.checked ? 1 : 0;
                onChange?.(arr);
              }}
            />
          },
        },
        {
          title: '分组',
          dataIndex: 'group',
          render: (val, record, index: number) => <Select
            placeholder="无分组"
            allowClear
            value={val}
            onChange={val => {
              const arr = [...value];
              arr[index].group = val;
              onChange?.(arr);
            }}
           options={dataGroups?.map(item=>{
             return {
               value: item,
               label: item,
             }
           })}
          />
        },
        {
          title: '名称',
          dataIndex: 'name',
          render: (val, record, index: number) => <Input
            placeholder="名称，非必填"
            value={val}
            maxLength={200}
            onChange={e => {
              const arr = [...value];
              arr[index].name = e.target.value;
              onChange?.(arr);
            }}
          />,
        },
        {
          title: '测试项',
          dataIndex: 'projectUuid',
          align: 'center',
          render: (val: string, _, index: number) => (
            <Select
              loading={getAllArticleDataTypeLoading}
              style={{ width: '200px' }}
              value={val}
              onChange={(val: string) => {
                const arr = [...value];
                arr[index].projectUuid = val;
                arr[index].data = '';
                arr[index].img = undefined;
                onChange?.(arr);
              }}
              options={getAllArticleDataTypeData?.map(item=>{
                return {
                  label: item.name,
                  value: item.uuid,
                }
              })}
            />
          ),
        },
        {
          title: '数据',
          key: 'data',
          align: 'center',
          render: (_, record, index) => {
            const type = getAllArticleDataTypeData?.find(item=>item.uuid === record.projectUuid);
            if(type?.type === EvaluationProjectType.DIGITAL){
              return <>
                <Upload
                  accept=".txt,.csv"
                  beforeUpload={file => {
                    if (
                      !['.txt', '.csv'].includes(
                        file.name.substr(file.name.lastIndexOf('.')),
                      )
                    ) {
                      message.error('只可以上传 TXT/CSV 格式的文件');
                      return false;
                    }
                    return true;
                  }}
                  showUploadList={false}
                  customRequest={({ file }) => {
                    const fileReader = new FileReader();
                    fileReader.readAsText(file as Blob, 'utf8');
                    fileReader.onload = () => {
                      const arr = [...value];
                      arr[index].data = (fileReader.result as string).trim();
                      onChange?.(arr);
                    };
                  }}
                >
                  <Button>
                    <UploadOutlined /> 选择txt文件
                  </Button>
                </Upload>
                {record.data && (
                  <>
                    <Divider type="vertical" />
                    <DataTextDetailBtn
                      data={record.data}
                      onDataChange={(data)=>{
                        const arr = [...value];
                        arr[index].data = data;
                        onChange?.(arr);
                      }}
                    />
                  </>
                )}
              </>
            }
            if(type?.type === EvaluationProjectType.IMG) {
              return <FileUpload value={record.img ? [record.img] : undefined} max={1} fileGroup={FileGroup.EVALUATION_DATA_IMG} onChange={(val) => {
                const arr = [...value];
                arr[index].img = val?.[0];
                onChange?.(arr);
              }}/>
            }
            if(type?.type === EvaluationProjectType.TABLE){
              return <TableModal value={record.json} onChange={(val)=>{
                const arr = [...value];
                arr[index].json = val;
                onChange?.(arr);
              }} rule={type.rule as any} />
            }
          },
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          width: 80,
          render: (_, record, index) => {
            // const type = getAllArticleDataTypeData?.find(item=>item.uuid === record.projectUuid);

            return <Space direction="vertical">
              {/* { type?.name === 'RAW FR 『原始频率响应』' && !!value[index].data &&
                <GenerateDataModal sourceData={value[index].data!} onConfirm={(data)=>{
                  const CFRType = getAllArticleDataTypeData?.find(item=>item.name === 'Compensated FR 『补偿频率响应』');

                  onChange?.([
                    ...value,
                    {
                      key: Math.random(),
                      projectUuid: CFRType!.uuid,
                      data,
                      name: value[index].name,
                      desc: '',
                      defaultShow: 1,
                    },
                  ]);
                }} />
              } */}
              <Button
                danger
                type="primary"
                size="small"
                onClick={() => {
                  const arr = [...value];
                  arr.splice(index, 1);
                  onChange?.(arr);
                }}
              >
                <MinusOutlined />
              </Button>
            </Space>
          }

        },
      ]}
      dataSource={value}
      pagination={false}
      expandable={{
        expandedRowRender: (record, index) => (
          <TextArea
            placeholder="描述，5000字以内"
            value={record.desc}
            autoSize
            maxLength={5000}
            showCount
            onChange={e => {
              const arr = [...value];
              arr[index].desc = e.target.value;
              onChange?.(arr);
            }}
          />
        ),
        defaultExpandAllRows: true,
      }}
      footer={() => (
        <Button
          block
          onClick={() => {
            onChange?.([
              ...value,
              {
                key: Math.random(),
                group: DEFAULT_DATA_GROUP,
                projectUuid: '',
                data: '',
                desc: '',
                name: '',
                defaultShow: 1,
              },
            ]);
          }}
        >
          <PlusOutlined />
        </Button>
      )}
      components={{
        body: {
          wrapper: getBody,
          row: getRow,
        },
      }}
    />
  );
};
